namespace SB2.Core;

/// <summary>
/// 动态函数入口服务
/// </summary>
public class DynamicFunctionSrv
{
    private readonly IDynamicFunction _srv;
    private readonly ISqlSugarClient _dbContext = Furion.App.GetService<ISqlSugarClient>();
    private readonly INamedServiceProvider<IDynamicFunction> namedServiceProvider = Furion.App.GetService<INamedServiceProvider<IDynamicFunction>>();
    /// <summary>
    /// 函数信息
    /// </summary>
    /// <value></value>
    public DynamicFunction Function { get; private set; }
    /// <summary>
    /// 函数对应脚本信息
    /// </summary>
    /// <value></value>
    public DynamicFunctionScript Script { get; private set; }
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="Id">动态函数id</param>
    public DynamicFunctionSrv(long Id)
    {
        Function = _dbContext.Queryable<DynamicFunction>().First(m => m.DynamicFunctionID == Id);
        if (Function == null)
        {
            throw new Exception("函数不存在！");
        }

        _srv = namedServiceProvider.GetService<ITransient>(Function.FileType);
        if (_srv == null)
        {

            throw new Exception("函数类型有误！");
        }
        Script = _dbContext.Queryable<DynamicFunctionScript>().First(m => m.DynamicFunctionScriptID == Function.DynamicFunctionScriptID);

        // Console.WriteLine(Function.ToJson());
        if (Script == null)
        {
            throw new Exception("脚本不存在！");
        }
    }
    /// <summary>
    /// 运行函数
    /// </summary>
    /// <param name="param">函数参数 多为json格式字符串</param>
    /// <returns></returns>
    public async Task<object> RunAsync(object param)
    {

        // var user = App.User.KnxUser();
        var p = new DynamicFunctionTempData
        {
            Request = param,
            Context = new
            {
                // user.CustomerCode,
                // user.UserID,
                // user.Language,
                // user.EmpInfo.EmpID
            }
        };
        Console.WriteLine("=========" + _srv.GetType());
        // 记录日志todo
        var startDate = DateTime.Now;
        var res = await _srv.RunAsync(new DynamicFunctionExcDto { Function = Function, Script = Script, Param = p });
        var spendTime = (DateTime.Now - startDate).TotalMilliseconds;
        Console.WriteLine($"====== 耗时： {spendTime} 毫秒");
        // 更新日志 todo 
        return res;
    }
    /// <summary>
    /// 运行函数
    /// </summary>
    /// <param name="param">函数参数 多为json格式字符串</param>
    /// <returns></returns>
    public object Run(object param)
    {
        return RunAsync(param).GetAwaiter().GetResult();
    }
}